// 认证检查脚本
(function() {
    'use strict';
    
    // 检查URL中是否有认证标记
    function hasAuthToken() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('auth') !== null;
    }
    
    // 添加登出功能
    function logout() {
        localStorage.removeItem('telchinaAuth');
        sessionStorage.removeItem('telchinaAuth');
        window.location.href = '/login.html';
    }
    
    // 在页面中添加登出按钮
    function addLogoutButton() {
        // 查找导航栏
        const nav = document.querySelector('nav .flex.items-center.space-x-4');
        if (nav && !nav.querySelector('.logout-btn')) {
            // 创建登出按钮
            const logoutBtn = document.createElement('button');
            logoutBtn.innerHTML = `
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                </svg>
                登出
            `;
            logoutBtn.className = 'logout-btn text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium flex items-center cursor-pointer';
            logoutBtn.onclick = logout;
            
            nav.appendChild(logoutBtn);
        }
    }
    
    // 处理URL中的认证标记
    function handleAuthToken() {
        if (hasAuthToken()) {
            const loginData = {
                isLoggedIn: true,
                username: 'admin',
                loginTime: new Date().getTime(),
                apiToken: 'your-secret-token'
            };
            sessionStorage.setItem('telchinaAuth', JSON.stringify(loginData));
            
            // 移除URL中的auth参数
            const url = new URL(window.location);
            url.searchParams.delete('auth');
            window.history.replaceState({}, document.title, url.toString());
        }
    }
    
    // 页面初始化
    function initPage() {
        // 处理认证标记
        handleAuthToken();
        
        // 添加登出按钮（如果有登录状态）
        const authData = localStorage.getItem('telchinaAuth') || sessionStorage.getItem('telchinaAuth');
        if (authData) {
            try {
                const loginData = JSON.parse(authData);
                if (loginData.isLoggedIn) {
                    addLogoutButton();
                }
            } catch (e) {
                // 忽略解析错误
            }
        }
    }
    
    // 页面加载时执行初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initPage);
    } else {
        initPage();
    }
    
    // 将logout函数暴露到全局，以便其他脚本调用
    window.telchinaLogout = logout;
 })();